package com.szz.cardecision.controller;

import com.szz.cardecision.entity.Feedback;
import com.szz.cardecision.entity.PointsTransaction;
import com.szz.cardecision.entity.User;
import com.szz.cardecision.mapper.FeedbackMapper;
import com.szz.cardecision.mapper.PointsTransactionMapper;
import com.szz.cardecision.mapper.UserMapper;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;

@Controller
public class FeedbackController {
    private final FeedbackMapper feedbackMapper;
    private final UserMapper userMapper;
    private final PointsTransactionMapper pointsTransactionMapper;

    public FeedbackController(FeedbackMapper feedbackMapper, UserMapper userMapper, PointsTransactionMapper pointsTransactionMapper) {
        this.feedbackMapper = feedbackMapper;
        this.userMapper = userMapper;
        this.pointsTransactionMapper = pointsTransactionMapper;
    }

    @PostMapping("/consult/{id}/feedback")
    public String submitFeedback(@PathVariable Long id,
                                 @RequestParam(required = false) Integer rating,
                                 @RequestParam(required = false) String comment,
                                 Authentication auth,
                                 Model model) {
        User user = userMapper.findByUsername(auth.getName()).orElseThrow();
        Feedback fb = new Feedback();
        fb.setConsultationId(id);
        fb.setUserId(user.getId());
        fb.setRating(rating);
        fb.setComment(comment);
        fb.setCreatedAt(LocalDateTime.now());
        feedbackMapper.insert(fb);

        // award points for feedback
        user.setPoints((user.getPoints() == null ? 0 : user.getPoints()) + 2);
        userMapper.update(user);

        PointsTransaction tx = new PointsTransaction();
        tx.setUserId(user.getId());
        tx.setChangeAmount(2);
        tx.setReason("反馈咨询");
        tx.setCreatedAt(LocalDateTime.now());
        pointsTransactionMapper.insert(tx);

        return "redirect:/consult/" + id;
    }
}